// pages/member/coupon_v2/coupon_v2.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    selected: 0,
    selectedidx: '1',
    page: 1,
    pageSize: 10,
    total_page: 0,
    isPresenter: false,
    //待使用
    wait_used: [],
    overdue: [],
    used: [],
    usermessage: {
      value: '',
      item: '',
      index: ''
    },
    presentershow: false,
    display: 99999,
    listData: [{
      type: 1
    },
    {
      type: 2
    },
    {
      type: 3
    },
    {
      type: 4
    },
    {
      type: 5
    },
    {
      type: 6
    },
    {
      type: 7
    }
    ],
    bottomIndex: '',
    // types:['全部','平台','门店','酒店','指定商品','分类商品','兑换卷','满减卷','折扣卷','快过期'],
    types: [],
    typesIndex: 0,
    kFootshow: true,
    write_off_coupon: false,
    share_coupon: false,
    combine_show: false,

    couponListDataSet: [], //数据集
    couponListData: [],
    colors: ['#fbbd5c', '#ff8383', '#a291ff', '#f095ed', '#6dccf8', '#fb946c', '#cecece']

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  tapGo(e) {
    if (this.data.selectedidx == '1') {

      // let info = JSON.stringify(e.currentTarget.dataset.info);
      let info = e.currentTarget.dataset.info;
      // let mun;
      if (this.data.isPresenter) {
        info.isPresenter = this.data.isPresenter;
      }
      if (info.num) {
        //&share=${this.data.share_coupon} &share=${this.data.share_coupon}
        wx.navigateTo({
          url: `/packageA/member/coupon_v2_detail/coupon_v2_detail?id=${info.id}&combine=${info.combine}&combine_show=${this.data.combine_show}`,
        });
      } else {
        wx.navigateTo({
          url: `/packageA/member/coupon_v2_detail/coupon_v2_detail?id=${info.id}&combine=${info.combine}&combine_show=${this.data.combine_show}`,
        });
        // info.num = '1';
        // wx.navigateTo({
        //   url: '/packageA/member/coupon_v2_detail/coupon_v2_detail?info=' + JSON.stringify(info) + '&combine=' + this.data.combine,
        // });
      }
    }

  },
  showButton(evt) {
    let index = evt.detail;
    console.log(evt.detail);
    if (this.data.selectedidx == 1) {
      this.data.wait_used[index].openIs = !this.data.wait_used[index].openIs;
      this.setData({
        wait_used: this.data.wait_used
      });
    } else if (this.data.selectedidx == 2) {
      this.data.overdue[index].openIs = !this.data.overdue[index].openIs;
      this.setData({
        overdue: this.data.overdue
      });
    } else if (this.data.selectedidx == 3) {
      this.data.used[index].openIs = !this.data.used[index].openIs;
      this.setData({
        used: this.data.used
      });
    }
  },
  setTypesIndex(evt) {
    let index = evt.currentTarget.dataset.index;
    if (index == this.data.typesIndex) return;
    this.setData({
      typesIndex: index
    });
    this._getNetData(this.data.selectedidx, index);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._initData();
    this._getNetData(1, this.data.typesIndex);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData(this.data.selectedidx, this.data.typesIndex);
    } else {
      console.log('没有更多数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  onShareTimeline(){},
  getmemberInfo(e) {
    let val = e.detail.value;
    var that = this;
    let urlStr = app.getNetAddresss("member.member.memberInfo");
    urlStr += '&uid=' + val;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            memberInfo: res.data.nickname ? res.data.nickname : ''
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //发起http请求
  _getNetData(type, coupon_type) {
    if (wx.tempCqSwipeCell) {
      wx.tempCqSwipeCell.setData({
        prevBox: 0
      });
    }
    this.setData({
      couponListData: [],
    });
    let that = this;
    this.data.page = 1;
    let urlStr = app.getNetAddresss("coupon.member-coupon.coupons-of-member-by-status-v2");

    if (app.globalData.store_alone_temp == 1) {
      // 开启门店独立模块
      urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.coupon.coupons-of-member-by-status-v2");
    }

    urlStr += "&status_request=" + type;
    urlStr += "&coupon_type=" + coupon_type;
    urlStr += "&page=1";
    app._getNetWork({
      url: urlStr,
      success: (resdata)=> {
        var res = resdata.data;
        if (res.result == 1) {
          var myData = res.data;
          that.page = 1;
          that.data.total_page = res.data.data.total ? res.data.data.total : 0;
          that.data.couponListDataSet = myData.data.data;
          that.isLoadMore = true;
          if (res.data.set) {
            that.setData({
              isPresenter: res.data.set.transfer
            });
          }

          if (res.data.search_array) {
            that.setData({
              types: res.data.search_array || []
            });
            for (let i = 0; i < myData.data.data.length; i++) {
              myData.data.data[i].openIs = false;
              myData.data.data[i].ind = i;
              if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '门店商品') {
                myData.data.data[i].type = 6;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '平台商品') {
                myData.data.data[i].type = 1;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '兑换券') {
                myData.data.data[i].type = 2;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '分类商品') {
                myData.data.data[i].type = 3;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '指定商品') {
                myData.data.data[i].type = 4;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '酒店商品') {
                myData.data.data[i].type = 5;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '商品和门店') {
                myData.data.data[i].type = 8;
              }
            }
          }

          that.setData({
            couponListData: that.data.couponListDataSet,
            combine_show:res.data.combine_show
          });
          if(!app._isTextEmpty(myData.share_coupon)){
            this.setData({
              share_coupon:myData.share_coupon
            })
          }

        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  _getMoreData(type, coupon_type) {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      // that.loading = true;
      return;
    } else {
      this.data.page += 1;
      let urlStr = app.getNetAddresss("coupon.member-coupon.coupons-of-member-by-status-v2");
      if (app.globalData.store_alone_temp == 1) {
        // 开启门店独立模块
        urlStr = app.getNetAddresss("plugin.store-alone-temp.frontend.coupon.coupons-of-member-by-status-v2");
      }

      urlStr += "&status_request=" + type;
      urlStr += "&coupon_type=" + coupon_type;
      urlStr += "&page=" + this.data.page;
      app._getNetWork({
        url: urlStr,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            var myData = res.data;
            for (let i = 0; i < myData.data.data.length; i++) {
              myData.data.data[i].openIs = false;
              myData.data.data[i].ind = this.data.couponListDataSet.length + i;
              if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '门店商品') {
                myData.data.data[i].type = 6;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '平台商品') {
                myData.data.data[i].type = 1;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '兑换券') {
                myData.data.data[i].type = 2;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '分类商品') {
                myData.data.data[i].type = 3;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '指定商品') {
                myData.data.data[i].type = 4;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '酒店商品') {
                myData.data.data[i].type = 5;
              } else if (myData.data.data[i].belongs_to_coupon.coupon_type_name == '商品和门店') {
                myData.data.data[i].type = 8;
              }
            }
            this.isLoadMore = true;
            this.setData({
              couponListData: this.data.couponListDataSet.concat(myData.data.data),
            });
          } else {
            this.isLoadMore = false;
            wx.showToast({
              icon: 'none',
              title: res.msg,
              duration: 1000
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  //切换优惠券状态列表
  switchItem(e) {
    let index = e.detail.index;
    if ((index + 1) == this.data.selectedidx) return;
    if (index == 0) {
      this.setData({
        selectedidx: '1'
      });
    } else if (index == 1) {
      this.setData({
        selectedidx: '2'
      });
    } else if (index == 2) {
      this.setData({
        selectedidx: '3'
      });
    }
    this._initData();
    console.log(this.data.typesIndex);
    this._getNetData(this.data.selectedidx, this.data.typesIndex);
  },
  _initData() {
    this.setData({
      page: 1,
      goload: true,
      total_page: 0,
      allLoaded: false,
      isLoadMore: true,
      isPresenter: false
    });

  },
  presenterOnce(e) {
    console.log(e);
    let item = e.detail.item;
    let ind = e.detail.ind;
    this.presenter(item, ind);
  },
  //赠送优惠券
  presenter(item, index) {
    let that = this;
    // let item = e.currentTarget.dataset.item;
    // let index = e.currentTarget.dataset.index;
    that.setData({
      'usermessage.value': '',
      'usermessage.item': '',
      'usermessage.index': '',
      memberInfo: ''
    });
    that.setData({
      'usermessage.item': item,
      'usermessage.index': index,
      'presentershow': true
    });
  },
  onconfirm(event) {
    let that = this;
    if (app._isTextEmpty(this.data.usermessage.value)) {
      wx.showToast({
        icon: 'none',
        title: '用户ID不能为空',
        duration: 1000
      });
      this.setData({
        presentershow: false
      });
      return;
    }
    that._presenterPost(this.data.usermessage.value, this.data.usermessage.item, this.data.usermessage.index);
  },
  onclose(event) {
    let that = this;
    that.setData({
      'usermessage.value': '',
      'usermessage.item': '',
      'usermessage.index': ''
    });
    that.setData({
      presentershow: false
    });
  },
  usermesbut: function (e) {
    let val = e.detail.value;
    this.setData({
      'usermessage.value': val
    });
  },
  //赠送post
  _presenterPost(value, item, index) {
    let that = this;
    let urlStr = app.getNetAddresss("coupon.coupon-transfer.index");
    urlStr += "&recipient=" + value;
    urlStr += "&record_id=" + item.id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (that.data.wait_used.length > 0) {
            let wait_used = that.data.wait_used;
            wait_used.splice(index, 1);
            that.setData({
              wait_used: wait_used
            });
            wx.showToast({
              icon: 'none',
              title: '操作成功',
              duration: 1500
            });
          }
          that.setData({
            presentershow: false
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          that.setData({
            presentershow: false
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  goBuyOnce(e) {
    let item = e.detail.item;
    let ind = e.detail.ind;
    this.goBuy(item, ind);
  },
  //通过类型去查询可用商品
  goBuy(item, ind) {
    // let item = e.currentTarget.dataset.item;
    if (item.belongs_to_coupon.use_type == 0) { //0商城通用
      this.goHome();
    } else if (item.belongs_to_coupon.use_type == 1) { //1指定分类
      wx.navigateTo({
        url: '/packageB/member/category/catelist/catelist?id=' + JSON.stringify(item.belongs_to_coupon.category_ids) +
          '&fromHome=1'
      });
    } else if (item.belongs_to_coupon.use_type == 2) { //2指定商品
      wx.navigateTo({
        url: '/packageB/member/category/search_v2/search_v2?coupon=' + item.belongs_to_coupon.id + '&fromHome=1'
      });
    } else if (
      item.belongs_to_coupon.use_type === 4 &&
      Array.isArray(item.belongs_to_coupon.storeids)
    ) {
      //4门店列表
      wx.navigateTo({
        url: '/packageC/o2o/o2oHome/o2oHome'
      });
    } else if (
      item.belongs_to_coupon.use_type === 5 &&
      typeof item.belongs_to_coupon.storeids === "number"
    ) {
      //5单门店
      wx.navigateTo({
        url: '/packageC/o2o/o2oStore/o2oStore?store_id=' + item.belongs_to_coupon.storeids
      });
    } else if (
      item.belongs_to_coupon.use_type === 7 &&
      Array.isArray(item.belongs_to_coupon.hotel_ids)
    ) {
      wx.navigateTo({
        url: '/packageC/hotel/HotelIndex/HotelIndex'
      });
    } else if (
      item.belongs_to_coupon.use_type === 6 &&
      typeof item.belongs_to_coupon.hotel_ids === "number"
    ) {
      wx.navigateTo({
        url: '/packageC/hotel/HotelHome/HotelHome?id=' + item.belongs_to_coupon.hotel_ids
      });
    } else if (
      item.belongs_to_coupon.use_type === 8
    ) {
      wx.navigateTo({
        url: '/packageB/member/category/search_v2/search_v2?keyword=' + item.belongs_to_coupon.goods_ids[0]
      });
    } else {
      this.goHome();
    }
  },
  goHome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  toggle(e) {
    let index = e.currentTarget.dataset.index;
    if (this.data.display == index) {
      this.setData({
        display: 99999
      });
    } else {
      this.setData({
        display: index
      });
    }
  },
  delteteItem(e) {
    console.log(e);
    let item = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    let urlStr = app.getNetAddresss("coupon.member-coupon.delete");
    urlStr += "&id=" + item.id;

    if (wx.tempCqSwipeCell) {
      wx.tempCqSwipeCell.setData({
        prevBox: 0
      });
    }
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          let couponListData = this.data.couponListData;
          couponListData.splice(index, 1);
          this.setData({
            couponListData
          });
          wx.showToast({
            icon: 'none',
            title: '操作成功',
            duration: 1000
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  gocouponStore() {
    //跳转到领卷中心
    wx.redirectTo({
      url: '/packageD/coupon/coupon_store'
    });
  },
  usermesbutInput(e) {
    let val = e.detail.value;
    this.data.usermessage.value = val;
  },
  tabrshowbtn(e) {
    let bol = e.detail;
    if (bol) {
      this.setData({
        kFootshow: false
      });
    }
  }
});